-- ============================================
-- POKER VIDEO - ComputerCraft / CC:Tweaked
-- Nécessite : Advanced Computer + Advanced Monitor (couleur)
-- ============================================

local SUITS = {
    { id = "H", symbol = "\3", color = colors.red },
    { id = "D", symbol = "\4", color = colors.red },
    { id = "C", symbol = "\5", color = colors.black },
    { id = "S", symbol = "\6", color = colors.black },
}
local RANKS = { "2","3","4","5","6","7","8","9","10","J","Q","K","A" }
local RANK_VALUE = {}
for i, r in ipairs(RANKS) do RANK_VALUE[r] = i + 1 end -- 2=2 ... A=14

local MISE = 1
local points = 100

local mon = peripheral.find("monitor")
if not mon then
    error("Aucun monitor trouve ! Colle un Advanced Monitor a cote du computer.")
end

mon.setTextScale(0.5)
local prevTerm = term.redirect(mon)
local w, h = term.getSize()

local function centerText(y, text, textColor, bgColor)
    term.setBackgroundColor(bgColor or colors.black)
    term.setTextColor(textColor or colors.white)
    local x = math.floor((w - #text) / 2) + 1
    term.setCursorPos(x, y)
    term.write(text)
end

-- === DECK ===
local deck = {}
local function buildDeck()
    deck = {}
    for _, suit in ipairs(SUITS) do
        for _, rank in ipairs(RANKS) do
            table.insert(deck, { rank = rank, suit = suit })
        end
    end
    for i = #deck, 2, -1 do
        local j = math.random(1, i)
        deck[i], deck[j] = deck[j], deck[i]
    end
end
local function drawFromDeck()
    if #deck == 0 then buildDeck() end
    return table.remove(deck)
end

-- === EVALUATION DE LA MAIN (5 cartes) ===
-- Retourne : nom de la main, multiplicateur de gain
local PAYTABLE = {
    { name = "Quinte flush",     mult = 50 },
    { name = "Carre",            mult = 25 },
    { name = "Full",             mult = 9 },
    { name = "Couleur",          mult = 6 },
    { name = "Quinte",           mult = 4 },
    { name = "Brelan",           mult = 3 },
    { name = "Double paire",     mult = 2 },
    { name = "Paire de Valets ou mieux", mult = 1 },
    { name = "Rien",             mult = 0 },
}

local function evaluateHand(hand)
    local counts = {}
    local suitsCount = {}
    local values = {}
    for _, card in ipairs(hand) do
        counts[card.rank] = (counts[card.rank] or 0) + 1
        suitsCount[card.suit.id] = (suitsCount[card.suit.id] or 0) + 1
        table.insert(values, RANK_VALUE[card.rank])
    end
    table.sort(values)

    local isFlush = false
    for _, c in pairs(suitsCount) do
        if c == 5 then isFlush = true end
    end

    local isStraight = true
    for i = 2, 5 do
        if values[i] ~= values[i - 1] + 1 then isStraight = false end
    end
    -- cas particulier : A-2-3-4-5
    if not isStraight then
        local lowAce = { 2, 3, 4, 5, 14 }
        local ok = true
        for i = 1, 5 do
            if values[i] ~= lowAce[i] then ok = false end
        end
        if ok then isStraight = true end
    end

    local pairs_, trips, quads = 0, 0, 0
    local highPairRank = nil
    for rank, c in pairs(counts) do
        if c == 2 then
            pairs_ = pairs_ + 1
            if RANK_VALUE[rank] >= RANK_VALUE["J"] then highPairRank = rank end
        elseif c == 3 then trips = trips + 1
        elseif c == 4 then quads = quads + 1 end
    end

    if isFlush and isStraight then return PAYTABLE[1] end
    if quads == 1 then return PAYTABLE[2] end
    if trips == 1 and pairs_ == 1 then return PAYTABLE[3] end
    if isFlush then return PAYTABLE[4] end
    if isStraight then return PAYTABLE[5] end
    if trips == 1 then return PAYTABLE[6] end
    if pairs_ == 2 then return PAYTABLE[7] end
    if pairs_ == 1 and highPairRank then return PAYTABLE[8] end
    return PAYTABLE[9]
end

-- === AFFICHAGE DES CARTES ===
local CARD_W, CARD_H = 6, 5
local handY = math.floor(h / 2) - 2
local held = { false, false, false, false, false }
local cardBoxes = {}

local function drawCard(x1, y1, card, isHeld)
    local x2, y2 = x1 + CARD_W - 1, y1 + CARD_H - 1
    term.setBackgroundColor(colors.white)
    for y = y1, y2 do
        term.setCursorPos(x1, y)
        term.write(string.rep(" ", CARD_W))
    end
    term.setTextColor(card.suit.color)
    term.setCursorPos(x1 + 1, y1 + 1)
    term.write(card.rank)
    term.setCursorPos(x1 + 2, y1 + 2)
    term.write(card.suit.symbol)
    term.setCursorPos(x2 - #card.rank, y2 - 1)
    term.write(card.rank)

    term.setBackgroundColor(isHeld and colors.lime or colors.gray)
    term.setTextColor(colors.black)
    term.setCursorPos(x1, y2 + 1)
    term.write(isHeld and " GARDE " or "       ")
end

local function drawHand(hand)
    local totalWidth = 5 * (CARD_W + 1) - 1
    local x = math.max(1, math.floor((w - totalWidth) / 2) + 1)
    cardBoxes = {}
    for i, card in ipairs(hand) do
        drawCard(x, handY, card, held[i])
        cardBoxes[i] = { x1 = x, x2 = x + CARD_W - 1, y1 = handY, y2 = handY + CARD_H + 1 }
        x = x + CARD_W + 1
    end
end

local function drawHeader(message, msgColor)
    term.setBackgroundColor(colors.black)
    term.clear()
    centerText(1, "=== CASINO COMPUTERCRAFT ===", colors.yellow)
    centerText(2, "POKER VIDEO", colors.white)
    centerText(3, "Points : " .. points, colors.lime)
    if message then
        centerText(4, message, msgColor or colors.white)
    end
end

-- === BOUTON ===
local actionButton = {}
local function drawActionButton(label, bg)
    local bw = #label + 4
    local x1 = math.max(1, math.floor((w - bw) / 2) + 1)
    local y = h - 1
    term.setBackgroundColor(bg)
    term.setTextColor(colors.white)
    for x = x1, math.min(w, x1 + bw - 1) do
        term.setCursorPos(x, y)
        term.write(" ")
    end
    term.setCursorPos(x1 + 2, y)
    term.write(label)
    actionButton = { x1 = x1, x2 = x1 + bw - 1, y = y }
end

-- === UNE MANCHE ===
local function playRound()
    if points < MISE then
        drawHeader("PLUS ASSEZ DE POINTS !", colors.red)
        sleep(2)
        return
    end
    points = points - MISE
    held = { false, false, false, false, false }

    local hand = {}
    for i = 1, 5 do hand[i] = drawFromDeck() end

    -- === ETAPE 1 : choix des cartes a garder ===
    while true do
        drawHeader("Touche les cartes a garder, puis ECHANGER")
        drawHand(hand)
        drawActionButton("ECHANGER", colors.orange)

        local event, side, x, y = os.pullEvent("monitor_touch")
        local clickedCard = nil
        for i, box in pairs(cardBoxes) do
            if x >= box.x1 and x <= box.x2 and y >= box.y1 and y <= box.y2 then
                clickedCard = i
                break
            end
        end

        if clickedCard then
            held[clickedCard] = not held[clickedCard]
        elseif x >= actionButton.x1 and x <= actionButton.x2 and y == actionButton.y then
            break
        end
    end

    -- === ETAPE 2 : echange des cartes non gardees ===
    for i = 1, 5 do
        if not held[i] then
            hand[i] = drawFromDeck()
        end
    end

    drawHeader("Nouvelle main :")
    drawHand(hand)

    local result = evaluateHand(hand)
    local gain = MISE * result.mult
    points = points + gain

    local msg, msgColor
    if gain > 0 then
        msg, msgColor = result.name .. " ! +" .. gain, colors.lime
    else
        msg, msgColor = result.name .. "... perdu !", colors.red
    end
    centerText(h - 1, msg, msgColor)
    sleep(3)
end

-- === ECRAN D'ACCUEIL ===
local startButton = {}
local function drawIdle()
    drawHeader()
    centerText(5, "Paytable : Quinte flush x50, Carre x25, Full x9,", colors.lightGray)
    centerText(6, "Couleur x6, Quinte x4, Brelan x3, 2 paires x2,", colors.lightGray)
    centerText(7, "Paire de Valets+ x1", colors.lightGray)

    local label = "MISER (" .. MISE .. " point) ET DISTRIBUER"
    local bw = #label + 4
    local x1 = math.max(1, math.floor((w - bw) / 2) + 1)
    local y = math.floor(h / 2) + 2
    term.setBackgroundColor(colors.green)
    term.setTextColor(colors.white)
    for x = x1, math.min(w, x1 + bw - 1) do
        term.setCursorPos(x, y)
        term.write(" ")
    end
    term.setCursorPos(x1 + 2, y)
    term.write(label)
    startButton = { x1 = x1, x2 = x1 + bw - 1, y = y }
end

-- === PROGRAMME PRINCIPAL ===
buildDeck()
drawIdle()

while true do
    local event, side, x, y = os.pullEvent("monitor_touch")
    if x >= startButton.x1 and x <= startButton.x2 and y == startButton.y then
        playRound()
        drawIdle()
    end
end